<template>
  <div>
    <page :asideShow="asideShow">
      <div slot="toolbar">
        <el-form :inline="true" :model="filters" label-width="90px" label-position="right">
          <el-form-item label="姓名：">
            <el-input
              placeholder="请输入"
              clearable
              v-model="filters.name"
              @keydown.enter.native="refreshPageRequest(1)"
            ></el-input>
          </el-form-item>
          <el-form-item label="选择小区:">
            <el-select
              v-model="filters.CID"
              filterable
              placeholder="请选择"
              clearable
              @change="refreshPageRequest(1)"
            >
              <el-option
                v-for="item in villageList"
                :key="item.CID"
                :label="item.name"
                :value="item.CID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="人员类型：">
            <el-select v-model="filters.type" placeholder="请选择" clearable>
              <el-option
                v-for="item in houseList"
                :key="item.DID"
                :label="item.name"
                :value="item.DID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标记类型：">
            <el-cascader
              :options="persign"
              @change="changeCascader"
              :props="{
                multiple: true,
                value: 'DID',
                label: 'name',
                children: 'dictionaries',
                checkStrictly: false,
                emitPath: true
              }"
              collapse-tags
              :show-all-levels="false"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="性别：">
            <el-select @change="refreshPageRequest(1)" v-model="filters.gender" placeholder="请选择" clearable>
              <el-option
                v-for="item in optionsSex"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="人员来源：">
            <el-select
              v-model="filters.registration"
              @change="refreshPageRequest(1)"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in registOption"
                :key="item.DID"
                :label="item.name"
                :value="item.DID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="政治面貌">
            <el-select v-model="filters.political" @change="refreshPageRequest(1)" placeholder="请选择" clearable>
              <el-option v-for="item in politics" :key="item.DID" :label="item.name" :value="item.DID"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="起始时间：">
            <el-date-picker
              class="normal"
              v-model="filters.startTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间：">
            <el-date-picker
              class="normal"
              v-model="filters.endTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="房屋：">
            <el-row style="width: 35%">
              <el-col :span="6">
                <el-input v-model="filters.buildName">
                  <span slot="suffix">栋</span>
                </el-input>
              </el-col>
              <el-col :span="6">
                <el-input v-model="filters.unitName">
                  <span slot="suffix">单元</span>
                </el-input>
              </el-col>
              <el-col :span="6">
                <el-input v-model="filters.floorName">
                  <span slot="suffix">层</span>
                </el-input>
              </el-col>
              <el-col :span="6">
                <el-input v-model="filters.houseName">
                  <span slot="suffix">号</span>
                </el-input>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <div slot="btnSearch" class="btn">
        <el-button @click="refreshPageRequest(1)" size="mini">查询</el-button>
        <el-button
          size="mini"
          type="primary"
          v-show="hasPerm('perhouse:person:add')"
          @click="handLedialogVisible('1')"
        >
          新增
        </el-button>
        <div class="BTN">
          <el-button :loading="downloadLoading" size="mini" type="success" v-show="hasPerm('perhouse:person:ept')" @click="exportQuery('1')">
            导出
          </el-button>
          <el-button
            size="mini"
            type="danger"
            v-show="hasPerm('perhouse:person:tsadd')"
            @click="handLedialogVisible('2')"
          >
            特殊新增
          </el-button>
        </div>
      </div>
      <div slot="content">
        <el-table
          :header-cell-style="{ background: '#e7eaf0', color: '#606266' }"
          :data="personList"
          max-height="680"
          stripe
          border
          style="width: 100%"
          v-loading="loading"
          element-loading-text="加载中..."
        >
          <el-table-column prop="photo" label="头像" width="100px" header-align="center" align="center">
            <template slot-scope="scope">
              <img
                :src="global.baseUrlImage + 'avatar/' + scope.row.photo"
                :onerror="$errorImgUrl"
                style="width: 50px; height: 50px"
                v-image-preview
              />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="80" header-align="center" align="center">
            <template slot-scope="scope">
              <span v-if="photoCheck == scope.row.photoCheck">
                {{ scope.row.name }}
              </span>
              <span v-else>{{ formatName(scope.row.name) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="gender" header-align="center" align="center" label="性别" width="50">
            <template slot-scope="scope">
              <div>
                <span v-if="scope.row.gender === 0">男</span>
                <span v-if="scope.row.gender === 1">女</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号码" width="120" header-align="center" align="center">
            <template slot-scope="scope">
              <span v-if="photoCheck == scope.row.photoCheck">
                {{ scope.row.phone }}
              </span>
              <span v-else>{{ hideOfString(scope.row.phone) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="idCard" label="证件号" width="120" header-align="center" align="center">
            <template slot-scope="scope">
              <span v-if="photoCheck == scope.row.photoCheck">
                {{ scope.row.idCard }}
              </span>
              <span v-else>{{ hideOfString(scope.row.idCard) }}</span>
            </template>
          </el-table-column>
          <el-table-column width="120" prop="CID" label="所在小区" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ getCIDName(scope.row.CID) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="人员类型" header-align="center" align="center" width="120">
            <template slot-scope="scope">
              <span>{{ typeToName(scope.row.type) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="registration" label="数据来源" width="100" header-align="center" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.registration ? getSourceName(scope.row.registration) : '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="address" label="人员地址" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.address ? scope.row.address : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="updateTime"
            label="注册时间"
            header-align="center"
            width="150"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div>
                <span>{{ $format(scope.row.updateTime) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="sign" label="标记类型" header-align="center" align="center" width="150">
            <template slot-scope="scope">
              <div>
                <span>{{ signTo(scope.row.sign) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="550"
            :label="$t('action.operation')"
          >addDialogVisible
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                v-show="hasPerm('perhouse:person:edit')"
                @click="
                  getCheckEncryption() ? get_sensitive_fields(scope.row, handeEdit) : (isCheckEncryption = true)
                "
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                type="warning"
                v-show="hasPerm('perhouse:person:detail')"
                @click="
                  getCheckEncryption() ? get_sensitive_fields(scope.row, checkPhoto) : (isCheckEncryption = true)
                "
              >
                查看
              </el-button>
              <el-button
                size="mini"
                type="success"
                @click="signSubmit(scope.row)"
                v-show="hasPerm('perhouse:person:sign')"
              >
                标记
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="getCheckEncryption() ? handleDelete(scope.row, 'out') : (isCheckEncryption = true)"
                v-show="hasPerm('perhouse:person:out')"
              >
                迁出
              </el-button>
              <el-button
                size="mini"
                type="danger"
                v-show="hasPerm('perhouse:person:delete')"
                @click="getCheckEncryption() ? handleDelete(scope.row) : (isCheckEncryption = true)"
              >
                删除
              </el-button>
              <el-button
                size="mini"
                type="info"
                v-show="hasPerm('perhouse:person:case')"
                @click.native.prevent="handlesick(scope.row)"
              >
                病例
              </el-button>
              <el-button
                size="mini"
                type="info"
                v-show="hasPerm('perhouse:person:hudang')"
                @click="
                  getCheckEncryption() ? get_sensitive_fields(scope.row, topage) : (isCheckEncryption = true)
                "
              >
                一人一档
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer">
        <el-pagination
          layout="total, prev, pager, next, jumper"
          @current-change="refreshPageRequest"
          :current-page="pageRequest.page"
          :page-size="pageRequest.limit"
          :total="totalSize"
          style="float: right"
        ></el-pagination>
      </div>
    </page>

    <!-- 病例 -->
    <div v-if="sddDialogVisible">
      <el-dialog title="病例添加" :visible.sync="sddDialogVisible" width="50%" :destroy-on-close="true">
        <el-form :model="sickform" class="addform" label-width="auto" label-position="left">
          <el-form-item label="病例选择：" prop="sickGroup">
            <el-checkbox-group v-model="sickform.sickGroup">
              <el-checkbox-button v-for="sick in sicklist" :label="sick" :key="sick">
                {{ sick.name }}
              </el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="体检时间" prop="sickTime">
            <el-date-picker
              v-model="sickform.sickTime"
              class="normal"
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
              clearable
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="sddDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sicksubmit">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 新增 -->
    <div v-if="addDialogVisible">
      <el-dialog title="人员新增" :visible.sync="addDialogVisible" width="50%" :destroy-on-close="true">
        <addPerson
          :propsForm="form"
          :SpecialNew="SpecialNew"
          @getMsg="addDialogVisible = false"
          @refresh="refresh()"
        ></addPerson>
      </el-dialog>
    </div>
    <!-- 标记 -->
    <el-dialog title="人员标记详情" width="28%" :visible.sync="dialogmarkVisible" :before-close="closeDiabrf">
      <perSign
        :signList="signList"
        :persignlist="persignlist"
        @handlebtn="closeDia"
        @closeDia="closeDiabrf"
      ></perSign>
    </el-dialog>
    <el-dialog title="详细信息" :visible.sync="dialogDetail" :before-close="handleCloses">
      <faimlyDetail ref="mychild"></faimlyDetail>
    </el-dialog>
    <el-dialog title="身份验证" :visible.sync="isCheckEncryption">
      <CheckEncryption @close="isCheckEncryption = false"></CheckEncryption>
    </el-dialog>
  </div>
</template>

<script>
import addPerson from './comments/addPerson';
import perSign from './comments/perSign';
import faimlyDetail from './comments/Detail.vue';
import { formatName } from '@/common/utils';
import CheckEncryption from '@/components/CheckEncryption';

export default {
  components: {
    addPerson,
    perSign,
    CheckEncryption,
    faimlyDetail
  },
  data() {
    return {
      isCheckEncryption: false,
      asideShow: false,
      downloadLoading: false,
      photoCheck: 0,
      selections: [],
      pageResult: [],
      sickform: {
        sickGroup: [],
        sickTime: '',
        CID: '',
        PID: ''
      },
      sickGroup: [],
      optionsSex: [
        {
          value: 0,
          label: '男'
        },
        {
          value: 1,
          label: '女'
        }
      ],
      filters: {
        CID: '',
        type: '',
        name: '',
        insertTime: '',
        updateTime: '',
        registration: '',
        gender: '',
        startTime: '',
        endTime: '',
        address: ''
      },
      pageRequest: {
        page: 1,
        limit: 10
      },
      loading: false,
      totalSize: 0,
      dialogDetail: false,
      // 新增或编辑弹框
      addDialogVisible: false,
      sddDialogVisible: false,
      operation: true,
      // 宽度
      formLabelWidth2: '140px',
      // 人员标记
      getNewList: [],
      registOption: [], //注册类型
      political: [],
      dictList: '',
      dialogmarkVisible: false,
      form: {},
      houseList: [],
      personList: [],
      // 小区列表
      villageList: [],
      // 数据来源
      source: [],
      // 标记已有列表
      signList: [],
      //新的标记列表
      newSignList: [],
      // 现有标记
      persignlist: [],
      formPass: {},
      sicklist: [],
      education: [],
      politics: [],
      persign: [],
      SpecialNew: false
    };
  },
  // dom加载完成触发事件
  async mounted() {
    this.villageList = await this.getCommunitiesMix();
    this.handleQuery();
    this.getDirList();
    this.$nextTick(() => {
      let dictList = JSON.parse(sessionStorage.getItem('dictData'));
      this.houseList = dictList.sys_person_type;
      this.signList = dictList.sys_person_sign;
      this.sicklist = dictList.sys_oldman_sick;
      this.source = dictList.sys_persion_source;
      this.education = dictList.sys_education_type;
      this.politics = dictList.sys_politics_type;
      this.persign = dictList.sys_person_sign;
    });
  },
  methods: {
    formatName(s) {
      return formatName(s);
    },
    getSourceName(id) {
      let rs = this.source.find((it) => it.DID === id);
      return rs && rs.name ? rs.name : '-';
    },
    typeToName(type) {
      for (let index = 0; index < this.houseList.length; index++) {
        var item = this.houseList[index];
        if (type === item.DID) {
          return item.name;
        }
      }
      return '-';
    },
    getCIDName(CID) {
      let rs = this.villageList.find((it) => it.CID === CID);
      return rs && rs.name ? rs.name : '-';
    },
    //病例体检
    sicksubmit() {
      let params = {};
      params.dbName = 'person_medical_history';
      params.info = this.sickform;
      this.$api.user.ywpt_data_edit(params).then((res) => {
        if (res.code == 0) {
          this.$message.success('操作成功');
          this.sddDialogVisible = false;
        } else {
          this.$message.warning('操作失败' + res.msg);
        }
      });
    },
    //跳转
    topage(row) {
      this.dialogDetail = true;
      let that = this;
      setTimeout(function () {
        that.$refs.mychild.parentHandleclick(row); //方法2
      }, 200);
    },
    handleCloses() {
      this.dialogDetail = false;
      this.$refs.mychild.closeWin(); //方法2
    },

    signTo(sign) {
      let list = this.getDictDataAll();
      if (sign && sign.length > 0) {
        let name = '';
        for (let i = 0; i < sign.length; i++) {
          const ele = sign[i];
          // 对当前数据 sign 里面匹配的属性find到
          let obj = list.find((v) => {
            return v.DID == ele;
          });
          name += obj.name + '/';
        }
        //出除字符串最后一位
        if (name.length > 0) name = name.substring(0, name.length - 1);
        return name;
      }
      return '-';
    },
    //数据更改新增刷新
    refresh() {
      this.addDialogVisible = false;
      this.handleQuery();
    },

    getDirList() {
      //调用字典
      this.dictList = JSON.parse(sessionStorage.getItem('dictData'));
      this.registOption = this.dictList.sys_persion_source;
      this.registOption.map((item) => {
        item.value = item.DID;
        item.name = item.name;
      });
    },

    //级联选择
    changeCascader(e) {
      let arr = [];
      arr = e.map((item) => {
        return item[1];
      });
      this.filters.sign = arr;
    },
    // 获取人员列表 从各个调用改方法的地方可以确定该函数为页面获取数据的方法
    async handleQuery(val) {
      // loading 打开
      this.loading = true;
      let params = Object.assign(this.filters, {
        page: val ? '' : this.pageRequest.page,
        limit: val ? '' : this.pageRequest.limit
      });
      params.auditStatus = 1;
      let res = await this.$api.personnel.queryList(params);
      if (res.code !== 0) {
        this.loading = false;
        this.$message({
          type: 'error',
          message: '获取列表失败' + err.msg
        });
        return;
      }
      this.loading = false;
      this.personList = res.data;
      this.totalSize = res.count;
      this.personList.forEach((item, index) => {
        item.photoCheck = index + 1;
      });
    },

    // 导出
    exportQuery() {
      if (!this.filters.CID) {
        this.$message({ message: '请选择小区', type: 'error' })
      }else {
        this.$confirm('确认导出选中记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.downloadLoading = true
          this.$api.wxNotic.export_xq(this.filters.CID).then((res) => {
            let obj = this.villageList.find((item) => {
              this.downloadLoading = false
              return this.filters.CID == item.CID;
            });
            let name = '导出数据';
            if (obj) name = obj.name; // 小区名字
            var a = document.createElement('a');
            a.download = name + '.zip';
            a.href = URL.createObjectURL(res);
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
          });
        });
      }
    },

    // 新增界面 isSpecial 1 普通 2 特殊
    handLedialogVisible(isSpecial) {
      this.SpecialNew = isSpecial == '2' ? true : false;
      this.addDialogVisible = true;
      this.operation = true;
      this.form = {};
    },
    //编辑界面
    handeEdit(row) {
      console.log(row.idCard);
      this.addDialogVisible = true;
      this.operation = false;
      this.form = Object.assign({}, row);
    },

    // 分页 每次更改页面参数 调用该函数
    refreshPageRequest(page) {
      this.pageRequest.page = page;
      this.handleQuery();
    },
    //病例
    handlesick(row) {
      this.sickform.CID = row.CID;
      this.sickform.PID = row.PID;
      this.sddDialogVisible = true;
    },

    // 删除
    handleDelete(row, type) {
      var par = {
        IDS: row.PID
      };
      let msg = '确认删除选中记录吗？';
      if (type) {
        par.operation = type;
        msg = '确认迁出选中记录吗？';
      }

      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.personnel.batchDelete(par).then((res) => {
          if (res.code == 0) {
            this.$message({ message: '删除成功', type: 'success' });
            this.handleQuery();
          } else {
            this.$message({
              message: '操作失败, ' + res.msg,
              type: 'error'
            });
          }
        });
      });
    },
    //查看电话号码
    checkPhoto(row) {
      if (row.photoCheck === this.photoCheck) {
        this.photoCheck = 0;
      } else {
        this.$nextTick(() => {
          //nextTick并不是用来监听DOM变更，它的作用是一次性更改数据，并且渲染DOM
          this.$set(this.personList, this.photoCheck - 1, row);
        });
        this.photoCheck = row.photoCheck;
      }
    },

    // 标记
    signSubmit(row) {
      this.dialogmarkVisible = true;
      this.persignlist = row;

      if (!this.persignlist.sign) {
        this.persignlist.sign = [];
      }
    },

    checkboxChange(id) {
      this.newSignList.map((item) => {
        if (item.DID == id) {
          item.label = !item.label;
        }
      });
    },
    closeDiabrf() {
      this.dialogmarkVisible = false;
    },
    // 关闭弹出框触发事件
    closeDia() {
      this.dialogmarkVisible = false;
      this.handleQuery();
    }
  }
};
</script>
<style lang="scss" scoped>
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
.addform {
  margin: 0 auto;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
  justify-content: space-between;
  .el-form-item {
    width: 48%;
  }
  .el-form-item__content {
    .el-cascader {
      width: 100%;
    }
    .el-select {
      width: 100%;
    }
  }
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
.el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin: 10px;
}
.btn {
  width: 1000px;
  margin: 3px;
  margin-left: 0px;
}
.BTN {
  margin-top: 10px;
}
</style>
